package leetcode.year2021.month10;

import java.util.List;

/**
 * 23. 合并K个升序链表
 */
public class _11_01MergeKLists23 {
  public ListNode mergeKLists(ListNode[] lists) {
    if (lists.length == 0){
      return null;
    }
    ListNode dummy = new ListNode(0);
    for (int i = 0; i < lists.length; i++) {
      dummy.next = mergeTwoList(dummy.next, lists[i]);

    }
    return dummy.next;
  }

  private ListNode mergeTwoList(ListNode l1, ListNode l2) {
    if (l1 == null) {
      return l2;
    }
    if (l2 == null) {
      return l1;
    }
    ListNode dummy = new ListNode();

    ListNode curr = dummy;

    while (l1 != null || l2 != null) {
      if (l1 == null) {
        curr.next = l2;
        l2 = l2.next;
      } else if (l2 == null) {
        curr.next = l1;
        l1 = l1.next;
      } else if (l1.val > l2.val) {
        curr.next = l2;
        l2 = l2.next;
      } else {
        curr.next = l1;
        l1 = l1.next;
      }
      curr = curr.next;
    }

    return dummy.next;
  }

  public class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }

  /**
   * 示例 1：
   *
   * 输入：lists = [[1,4,5],[1,3,4],[2,6]]
   * 输出：[1,1,2,3,4,4,5,6]
   * 解释：链表数组如下：
   * [
   *   1->4->5,
   *   1->3->4,
   *   2->6
   * ]
   * 将它们合并到一个有序链表中得到。
   * 1->1->2->3->4->4->5->6
   * 示例 2：
   *
   * 输入：lists = []
   * 输出：[]
   * 示例 3：
   *
   * 输入：lists = [[]]
   * 输出：[]
   *
   * 来源：力扣（LeetCode）
   * 链接：https://leetcode-cn.com/problems/merge-k-sorted-lists
   * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
   */
}
